/*!
 Temelia - B-tree samples.

 Copyright (C) 2008 Ceata (http://ceata.org/proiecte/temelia).

 @author Dascalu Laurentiu

 This program is free software; you can redistribute it and
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 3
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "include/samples.h"
#include <temelia/b_tree.h>

static void sample1()
{
	b_tree_t btree;
	b_tree_node_t root;
	int **x, i, N = 100, aux;

	PRINT("\n\n Sample 1 started \n\n");

	x = int_array_new(N, N);
	btree = b_tree_new(4);

	for (i = 0; i < N; i++)
	{
		b_tree_insert(btree, x[i], int_compare, NULL, 0);
		b_tree_level_order(btree, int_handler, NULL);
	}

	PRINT("%p %p %p %p %p\n", b_tree_get_root(btree), b_tree_get_min(btree),
			b_tree_get_min_key(btree), b_tree_get_max(btree),
			b_tree_get_max_key(btree));

	PRINT("Level order :\n");
	b_tree_level_order(btree, int_handler, NULL);

	PRINT("Indented show :\n");
	b_tree_show_indented(btree, int_level_handler, NULL);

	PRINT("Degree %d, Height %d\n", b_tree_get_degree(btree),
			b_tree_get_height(btree));

	root = b_tree_get_root(btree);

	PRINT("Root : %d %p %d %p %d %p\n", b_tree_node_get_depth(root),
			b_tree_node_get_parent(root),
			b_tree_node_get_children_number(root), b_tree_node_get_child(root,
					0), b_tree_node_get_keys_number(root), b_tree_node_get_key(
					root, 0));

	for (i = 0; i < N; i++)
	{
		if (b_tree_search(btree, x[i], int_compare, NULL) == NULL)
		{
			PRINT("B-tree error on line %d\n", __LINE__);
			exit(1);
		}
	}

	b_tree_level_order(btree, int_handler, NULL);

	PRINT("Started removing keys\n");
	PRINT("Current size %d\n", b_tree_get_size(btree));
	for (i = 0; i < N; i++)
	{
		aux = rand() % N;
		b_tree_remove(btree, x[aux], int_compare, NULL);
#ifdef DEBUG
		PRINT("Removing %d ==> %d\n", *(int *) x[aux], b_tree_remove(btree, x[aux], int_compare, NULL));
		b_tree_level_order(btree, int_handler, NULL);
		fgetc(stdin);
#endif
	}

	PRINT("New size %d\n", b_tree_get_size(btree));
	PRINT("\nIndented show :\n");
	b_tree_show_indented(btree, int_level_handler, NULL);

	b_tree_delete(btree);

	int_array_delete(x, N);

	PRINT("\n\n Sample 1 ended \n\n");
}

void run_b_tree_samples()
{
	sample1();
}
